﻿using com.nm.library.Excels;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.library;
using System.Data;
using com.nm.db.Models.Terminal;
using com.nm;
using george.Helper;
using com.nm.library.Helper;
using TerminalAPI.models;

namespace TerminalAPI.ImportExcel
{
    [Export(typeof(ExcelImport))]
    public class ShopShelfExcel : ExcelImport
    {
        public override Dictionary<string, ImportVerify> DictFields => dictFields;


        /// <summary>
        /// Excel字段映射
        /// </summary>
        private static Dictionary<string, ImportVerify> dictFields = new List<ImportVerify> {
            new ImportVerify{ ColumnName="店铺编号",FieldName="ShopCode",DataType=typeof(string),VerifyFunc =(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,30,true,true)},
            new ImportVerify{ ColumnName="店铺名称",FieldName="ShopName",DataType=typeof(string),VerifyFunc =(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,50,false,true)},
            new ImportVerify{ ColumnName="货架编号",FieldName="GSCode",DataType=typeof(string),VerifyFunc =(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,30,true,true)},
            new ImportVerify{ ColumnName="货架名称",FieldName="GSName",DataType=typeof(string),VerifyFunc =(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,50,false,true)},
            new ImportVerify{ ColumnName="货架数量",FieldName="Qty",DataType=typeof(int),VerifyFunc=(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,5,true,true) }
           }.ToDictionary(e => e.ColumnName, e => e);

        public override ExcelImportType Type => ExcelImportType.SHOPSHELF;

        public override object SaveImportData(DataTable dt, Dictionary<string, object> extraInfo, int userId)
        {
            var index = dt.Rows.Count;
            var msg = $"成功导入{index}条数据";
            try
            {
                var dc = new TerminalEntities();
                foreach (DataRow item in dt.Rows)
                {
                    #region 校验
                    var ShopCode = item["ShopCode"].ToString().ToUpper().Trim();
                    var GSCode = item["GSCode"].ToString().StartTrim();
                    var qty = Convert.ToInt16(item["Qty"].ToString());
                    #endregion
                    var goods = dc.Tm_GoodShelf.FirstOrDefault(t => t.GSCode == GSCode);
                    if (goods == null)
                    {
                        return new ImportResult()
                        {
                            IsSuccess = false,
                            ExtraInfo = "数据校验错误",
                            Message = $"数据错误,没有找到编号为【{GSCode}】的货架信息"
                        };
                    }
                    var query = dc.Tm_ShopShelf.FirstOrDefault(t => t.ShopCode == ShopCode && t.SGID == goods.GSID);
                    if (query != null)
                    {
                        if (query.Qty != qty)
                        {
                            SysChangeLog.WriteLog(userId, 1, ShopCode, "店铺货架数量变更-平台导入", $"店铺:{item["ShopName"].ToString() }数量从{query.Qty}变更为{userId}.");
                        }
                        query.Qty = qty;
                        query.ShopCode = ShopCode;
                        query.ShopName = item["ShopName"].ToString();
                        query.ModifyDate = DateTime.Now;
                        query.SGID = goods.GSID;
                    }
                    else
                    {
                        var shop = new Tm_ShopShelf
                        {
                            Qty = qty,
                            CreateDate = DateTime.Now,
                            ShopCode = ShopCode,
                            ShopName = item["ShopName"].ToString(),
                            IsRemove = false,
                            ModifyDate = DateTime.Now,
                            Operator = userId,
                            SGID = goods.GSID
                        };
                        dc.Tm_ShopShelf.Add(shop);
                    }
                }
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return new ImportResult()
                {
                    IsSuccess = false,
                    ExtraInfo = ex,
                    Message = ex.Message
                };
            }
            return new ImportResult()
            {
                IsSuccess = true,
                ExtraInfo = "导入成功",
                Message = msg
            };
        }

        public override DataTable GetExportData(string Keys)
        {
            var dc = new TerminalEntities();
            string strSql = $@"select ShopCode,ShopName,GsName,GsCode,Qty from Tm_ShopShelf ss
left join
Tm_GoodShelf gs
on ss.SGID = gs.gsid
where
ss.IsRemove = 0
and qty > 0
{(string.IsNullOrWhiteSpace(Keys) ? "" : Keys + ")")}
order by shopname asc,gsname asc,qty desc
";
            var result = dc.Database.SqlQuery<ExportModel>(strSql);
            return DataTableHelper.LinqToDataTable(result);
        }
    }
}

